package com.dyh.quickdemozwei.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: yhdong
 * @Date: 2021/12/10 17:43
 */
@Slf4j
@RequestMapping("/taskProcess")
@RestController
public class TestTaskProcessController {

    Map<String,SingeThreadProgress> cache=new HashMap<>();

    @RequestMapping("/newTask")
    public Object newTask(){
        List<String> datas = Lists.newArrayList(
                "1",
                "2",
                "3",
                "33",
                "77",
                "f"
        );
        SingeThreadProgress singeThreadProgress = new SingeThreadProgress(datas.size());
        cache.put("1919",singeThreadProgress);

        new WorkThread(datas,singeThreadProgress).start();
        return "ok";
    }

    /*ing*/
    @RequestMapping("/show")
    public Object show(){
        SingeThreadProgress singeThreadProgress = cache.get("1919");
        return singeThreadProgress;
    }


    @Setter@Getter
    class SingeThreadProgress{
        int index;
        int count;

        public SingeThreadProgress( int count) {
            this.count = count;
        }
    }

   class WorkThread  extends Thread{
       List<String> datas;
       SingeThreadProgress singeThreadProgress;

       public WorkThread(List<String> datas, SingeThreadProgress singeThreadProgress) {

           this.datas = datas;
           this.singeThreadProgress = singeThreadProgress;
       }


       @Override
       public void run() {
           for (String data : datas) {
               log.info("start handle {}",data);
               try {
                   Thread.sleep(1000L);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
               singeThreadProgress.index++;
               log.info("end handle {}",data);
           }

       }
   }
}
